package com.wltjack.sysmanage.common.aop;

import com.wltjack.sysmanage.common.DataSourceSwitch;
import com.wltjack.sysmanage.common.enums.DataSourceTypeEnum;
import com.wltjack.sysmanage.common.datasource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @ClassName DataSourceAspect
 * @Description aop的实现的数据源切换
 * @Author kangliang
 * @Date 2021/03/01 11:36
 * @Version 1.0
 */
@Order(value = -100)
@Slf4j
@Aspect
@Component
public class DataSourceAspect {

    @Pointcut("execution(* com.wltjack..service..*.*(..))")
    private void dbAspect() {
    }

    /**
     * 通过获取的注解，设置读取哪个数据源
     *
     * @param joinPoint
     */
    @Before("dbAspect()")
    public void db(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        DataSourceSwitch dataSourceSwitch = methodSignature.getMethod().getAnnotation(DataSourceSwitch.class);
        if (Objects.isNull(dataSourceSwitch) || Objects.isNull(dataSourceSwitch.value())) {
            DynamicDataSourceContextHolder.setDataSourceType(DataSourceTypeEnum.DB1);
        } else {
            DataSourceTypeEnum dataSourceTypeEnum = DataSourceTypeEnum.getDataSourceTypeEnumByCode(dataSourceSwitch.value().getCode());
            if (DataSourceTypeEnum.DB1.equals(dataSourceTypeEnum)) {
                DynamicDataSourceContextHolder.setDataSourceType(DataSourceTypeEnum.DB1);
            } else if (DataSourceTypeEnum.DB2.equals(dataSourceTypeEnum)) {
                DynamicDataSourceContextHolder.setDataSourceType(DataSourceTypeEnum.DB2);
            } else {
                DynamicDataSourceContextHolder.setDataSourceType(DataSourceTypeEnum.DB1);
            }

        }
    }

}

